package demo07.test2;

import demo04.personOperation.tool.ConnectionTool;
import demo04.personOperation.tool.Const;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.ArrayList;
import java.util.List;

public class ObjectOperation {

    public static void insertObject(Object object){

        Connection conn = null;
        PreparedStatement ps = null;

        List<Integer> toAddFieldIndexList = new ArrayList<>();

        //获取对象的Class类型
        Class objClass = object.getClass();

        //获取表名和列名
        String tableName = "";
        String fieldName = "";
        //判断此对象是否有注解 有的话获取注解的表名 没有的话直接将对象名获取当表名
        if (objClass.isAnnotationPresent(Table.class)){
            Table table = (Table) objClass.getDeclaredAnnotation(Table.class);
            tableName = table.value().toLowerCase();
        }else {
            //如果没有注解 就获取类名 那么此时类名与表名一致 并小写
            tableName = objClass.getSimpleName().toLowerCase();
        }

        try {
            //与数据库建立连接
            Class.forName(Const.DRIVER);
            conn = DriverManager.getConnection(Const.URL,Const.USERNAME,Const.PASSWORD);

            StringBuffer sb = new StringBuffer("insert into "+tableName+"(");

            Field[] fields = objClass.getDeclaredFields();

            for (int i = 0; i < fields.length; i++) {
                //获取遍历到当前位置的那个属性
                Field currentField = fields[i];
                if (currentField.isAnnotationPresent(PrimaryKey.class)){
                    PrimaryKey primaryKeyAnnotation = currentField.getDeclaredAnnotation(PrimaryKey.class);
                    if (currentField.isAnnotationPresent(Auto_Increment.class)){
                        Auto_Increment autoIncrement = currentField.getDeclaredAnnotation(Auto_Increment.class);
                        if (autoIncrement.equals(true)){
                            continue;
                        }
                    }
                }
                toAddFieldIndexList.add(i);

                fieldName = currentField.getName().toLowerCase();
                sb.append(fieldName+ (i==fields.length-1?")":","));

            }

            sb.append(" values(");

            //有多少个需要添加的属性，就有多少个问号
            for (int i = 1; i <= toAddFieldIndexList.size() ; i++) {
                sb.append(i==toAddFieldIndexList.size()?"?)":"?,");
            }
            //对这个sql语句进行预处理
            ps = conn.prepareStatement(sb.toString());

            //遍历所有的属性，获取这个对象中每个属性的值，分别设置相应问号
            for (int i = 0; i < toAddFieldIndexList.size() ; i++) {
                //获取数组中的第 i 个属性
                Field currentField = fields[toAddFieldIndexList.get(i)];
                //把所有的属性都设置为 私有 允许访问
                currentField.setAccessible(true);
                //从对象中获取相应属性的值
                Object fieldValue = currentField.get(object);
                //对相应的问号进行赋值
                ps.setObject(i+1,fieldValue);
            }
            int result = ps.executeUpdate();
            System.out.println(result);
        } catch (Exception e) {
            throw new RuntimeException();
        }finally {
            ConnectionTool.closed(conn,ps);
        }
    }

    public static void main(String[] args) {

        Students students = new Students(3,"mike",18);
        insertObject(students);
    }

}
